package com.tyf.bookreader.manager;

import com.tyf.bookreader.constant.RedisConstants;
import com.tyf.bookreader.service.RedisService;
import com.tyf.bookreader.utils.ImgVerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @Description 图形验证码生成，并放入redis中
 * @Author shallow
 * @Date 2023/4/1 18:17
 */
@Component
@Slf4j
public class CodeManager {
    @Autowired
    private RedisService redisService;

    /**
     * 获取图形验证码存入redis中
     * @param sessionId
     * @return
     * @throws IOException
     */
    public String getImgVerifyCode(String sessionId) throws IOException{
        String verifyCode = ImgVerifyCodeUtils.getRandomVerifyCode(4);
        String img = ImgVerifyCodeUtils.genVerifyCodeImg(verifyCode);
        redisService.set(RedisConstants.IMG_VERIFY_CODE_CACHE_KEY+sessionId, verifyCode, RedisConstants.IMG_VERIFY_CODE_CACHE_TIME);
        return img;
    }

    /**
     * 根据sessionId和输入匹配Redis中存储的验证码
     * @param sessionId
     * @param verifyCode
     * @return
     */
    public boolean imgVerifyCodeOk(String sessionId,String verifyCode){
        return Objects.equals(redisService.get(RedisConstants.IMG_VERIFY_CODE_CACHE_KEY+sessionId),verifyCode);
    }


}
